package com.jihox.abookpro;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jihox.abookpro.R;
import com.jihox.abookpro.adapter.DragAdapter;
import com.jihox.abookpro.adapter.PhotoGroupAdapter;
import com.jihox.abookpro.dao.BookTemplateDAO;
import com.jihox.abookpro.domain.BookProduct;
import com.jihox.abookpro.domain.BookProject;
import com.jihox.abookpro.domain.BookTemplate;
import com.jihox.abookpro.helper.BookHelper;
import com.jihox.abookpro.util.AlbumBean;
import com.jihox.abookpro.util.AndroidImageFile;
import com.jihox.abookpro.util.ConfigProperties;
import com.jihox.abookpro.util.DensityUtil;
import com.jihox.abookpro.util.NativeImageLoader;
import com.jihox.abookpro.view.DragGridView;
import com.jihox.abookpro.view.GalleryHorizontalView;
import com.jihox.abookpro.view.ShowPhotoImageView;
import com.jihox.abookpro.view.DragGridView.OnReorderItemsListener;
import com.jihox.abookpro.R.drawable;
/**
 *
 */
public class GallerySelectActivity extends BaseActivity {

	private List<AlbumBean> imageBeanList = new ArrayList<AlbumBean>();

	private PhotoGroupAdapter photoGroupAdapter;
	private GridView mGroupGridView;
	private int selected_photo_height = 180;
	private int selected_photo_width = 200;
	private GalleryHorizontalView galleryHorizontalView;
	private RelativeLayout relativeLayoutOfSelectedPhotoList ;

	public BookProject bookProject = null;
	private BookProduct bookProduct;
	private BookTemplate template = null;
	private String templateName;

	TextView selectedPhotoListNum;
	private Button nextStep;

	private DragGridView mDragGridView;
	private ImagesObserver imagesObserver;

	private DragAdapter mDragAdapter;
	private String[] captions;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_galleryselect);
		nextStep = (Button) findViewById(R.id.glsle_btnnext);

		templateName = getIntent().getStringExtra("templateName");
		if ((BookProduct) getIntent().getSerializableExtra("bookProduct") != null){
			bookProduct =(BookProduct) getIntent().getSerializableExtra("bookProduct");
			MyApplication.getInstance().setBookProduct(bookProduct);
		}else{
			bookProduct = MyApplication.getInstance().getBookProduct();
		}
		
		if (bookProduct == null){
			if(templateName == null){
				Intent intent = new Intent();   
				intent.setClass(GallerySelectActivity.this, HomeChangeActivity.class);   
				GallerySelectActivity.this.startActivity(intent);
				finish();
				return;
			}else{
				bookProduct = MyApplication.getInstance().getBookProject().getBook().getProduct();
				MyApplication.getInstance().setBookProduct(bookProduct);
				
			}
		}
		
		Bundle bundle = this.getIntent().getExtras();
		if(bundle!=null){
			captions = bundle.getStringArray("Captions");
		}
		BookTemplateDAO templateDao = new BookTemplateDAO(GallerySelectActivity.this);
		File file = new File(Environment.getExternalStorageDirectory(), ConfigProperties.getTemplatePath() +
                 templateName + "/" +
                 templateName +
                 ".xml");
		Log.d("File", file.getName() + "");
		template  = MyApplication.getInstance().getTemplate();
		if(template == null || !template.getTemplateName().equals(templateName)){
			if (Environment.getExternalStorageState().equals(
	                Environment.MEDIA_MOUNTED)) {
				if(file.exists()){
					try {
						FileInputStream inputStream = new FileInputStream(file);
						template = templateDao.retrieveBookTemplate(inputStream);
						template.setTemplateName(templateName);
						MyApplication.getInstance().setTemplate(template);
					} catch (Exception e) {
						Toast.makeText(GallerySelectActivity.this, getResources().getString(R.string.T_Read_Template_Error),
		                     Toast.LENGTH_SHORT).show();
					}
				}else{
					 Toast.makeText(GallerySelectActivity.this,
			                 "模板文件不存在", Toast.LENGTH_SHORT).show();
				}
	         }else {
	         // 此时SDcard不存在或者不能进行读写操作的
	         Toast.makeText(GallerySelectActivity.this,
	                 getResources().getString(R.string.T_No_SDCard), Toast.LENGTH_SHORT).show();
			 }
		}

		mGroupGridView = (GridView) findViewById(R.id.galleryselect_grid);
		if(firstScanFlag){
			getImages();
		}
		selectedPhotoListNum = (TextView) findViewById(R.id.selectedPhotoListTitle);
		relativeLayoutOfSelectedPhotoList = (RelativeLayout) findViewById(R.id.selectedPhotoList) ;
		galleryHorizontalView = (GalleryHorizontalView) findViewById(R.id.galleryHorizontalView);
		updateSelectedPhotoList();
		mGroupGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ShowImageActivity.currentScrollX = galleryHorizontalView.getScrollX();
				String childListName = imageBeanList.get(position).getFolderPath();
				Intent mIntent = new Intent(GallerySelectActivity.this, ShowImageActivity.class);
				mIntent.putExtra("childListName", childListName);
				mIntent.putExtra("folderName", imageBeanList.get(position).getFolderName());
				Bundle bundle = new Bundle();
				bundle.putStringArray("Captions", captions);
				mIntent.putExtras(bundle);
				startActivityForResult(mIntent,0);
			}
		});

		Button returnButton = (Button)findViewById(R.id.btnReturn); 
		returnButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent();   
				if (bookProduct.getCategory()==2){
					intent.putExtra("AblumHome", false);
				}
				
				intent.setClass(GallerySelectActivity.this, HomeChangeActivity.class);   
				GallerySelectActivity.this.startActivity(intent);
				NativeImageLoader.getInstance().clearCache();
				finish();
			}

		});

		nextStep.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View view) {
				gotoCurlActivity();
			}
		});
		imagesObserver = new ImagesObserver(new Handler()){
			@Override
			public void onChange(boolean selfChange) {
				getImages();
				updateSelectedPhotoList();
				//				checkSelectedList();
			}
		};
		this.getContentResolver().registerContentObserver( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, imagesObserver); 

		/*
		 * TODO: 要对observer 解除注册，放置内存泄露，acitivity也永远无法GC：  getContentResolver().unregisterContentObserver(yourObserver);
		 */

		TextView gallerySelectTitleTextView = (TextView) findViewById(R.id.gallery_select_title);
		gallerySelectTitleTextView.setText(getResources().getString(R.string.T_Select_text) + bookProduct.getNumOfPictures() + getResources().getString(R.string.T_Photo_text));
		invalidateNextStep();
		if(ShowImageActivity.selectedPhotoList.size() == bookProduct.getMaxPictures()){
			ShowImageActivity.showNextButton = true;
			nextStep.setEnabled(true);
			nextStep.setVisibility(View.VISIBLE);
		}
	}

	@Override  
	protected void onActivityResult(int requestCode, int resultCode, Intent data)  
	{  
		super.onActivityResult(requestCode, resultCode, data);  
		
		if (bookProduct==null){
			bookProduct = MyApplication.getInstance().getBookProduct();
		}
		//可以根据多个请求代码来作相应的操作  
		if(RESULT_OK==resultCode)  
		{  
			gotoCurlActivity();
		} else{
			doResume();
		}
	}  

	private void gotoCurlActivity(){
		if(ShowImageActivity.selectedPhotoList!=null&&ShowImageActivity.selectedPhotoList.size()==bookProduct.getNumOfPictures()){  
			nextStep.setEnabled(true);  

		}	else{  
			nextStep.setEnabled(false);  
		}
		// TODO Auto-generated method stub
		try {
			BookHelper bh = new BookHelper();
			Vector<File> images = new Vector<File>();
			for(AndroidImageFile u : ShowImageActivity.selectedPhotoList){
				images.add(new File(u.getPath()));
			}

			bookProject = bh.generateProject(bookProduct, template, images,getCacheDir().getPath());
			if (captions!= null && !(captions.length==0)){
				for (int i = 0; i < captions.length; i++)
					bookProject.getBook().getPages().get(0).getCaptions().get(i).setText(captions[i]);
			}
		} 
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Intent intent = new Intent();
		intent.setClass(GallerySelectActivity.this, CurlActivity.class);  
		Bundle mBundle = new Bundle();  
		MyApplication application = MyApplication.getInstance();
		application.setBookProject(bookProject);
		intent.putExtras(mBundle);
		intent.putExtra("templateName", templateName);//方便从SD卡中读取文件
		GallerySelectActivity.this.startActivity(intent); 
		NativeImageLoader.getInstance().clearCacheButTheSelectedPhotoList(ShowImageActivity.selectedPhotoList);
		
		finish();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		getContentResolver().unregisterContentObserver(imagesObserver);
		int count = mGroupGridView.getCount();
		for (int i = 0; i < count; i++) {
			RelativeLayout rl = (RelativeLayout) mGroupGridView.getChildAt(i);
			if (rl != null) {
				ShowPhotoImageView mImageView = (ShowPhotoImageView) rl
						.findViewById(R.id.group_image);

				if (mImageView != null) {
					BitmapDrawable bd = (BitmapDrawable)mImageView.getDrawable();
					mImageView.setImageResource(0);
					bd.setCallback(null);
					bd.getBitmap().recycle();
				}
			}
		}

		count = mDragGridView.getCount();
		for (int i = 0; i < count; i++) {
			RelativeLayout rl = (RelativeLayout) mDragGridView.getChildAt(i);
			if (rl != null) {
				ImageView mImageView = (ImageView) rl
						.findViewById(R.id.item_image);

				if (mImageView != null) {
					BitmapDrawable bd = (BitmapDrawable)mImageView.getDrawable();
					mImageView.setImageResource(0);
					bd.setCallback(null);
					bd.getBitmap().recycle();
				}
			}
		}
		System.gc();
		super.onDestroy();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent();    
			if (bookProduct.getCategory()==2){
				intent.putExtra("AblumHome", false);
			}
//			intent.setClass(GallerySelectActivity.this, ProductIntroductionActivity.class);   
			intent.setClass(GallerySelectActivity.this, HomeChangeActivity.class);  
			GallerySelectActivity.this.startActivity(intent);
			NativeImageLoader.getInstance().clearCache();
			finish();
		}
		return false;
	}

	protected void scanOKHandle(){
		photoGroupAdapter = new PhotoGroupAdapter(getApplicationContext(), imageBeanList = subGroupOfImage(mGroupMap), mGroupGridView);
		mGroupGridView.setAdapter(photoGroupAdapter);
		firstScanFlag = false;
	}

	@Override
	protected void onResume() {
		doResume();
		super.onResume();
	};

	private void doResume(){
		Resources resources = getResources();
		selected_photo_height = resources.getInteger(R.integer.selected_photo_height);
		selected_photo_height = DensityUtil.dip2px(this, selected_photo_height);
		selected_photo_width = resources.getInteger(R.integer.selected_photo_width);
		selected_photo_width = DensityUtil.dip2px(this, selected_photo_width);
		mDragGridView = (DragGridView) findViewById(R.id.dragGridView);

		LayoutParams params = new LayoutParams(
				ShowImageActivity.selectedPhotoList.size() *selected_photo_width, selected_photo_height);

		mDragGridView.setLayoutParams(params);
		mDragGridView.setColumnWidth(selected_photo_width);

		mDragGridView.setHorizontalSpacing(0);
		mDragGridView.setGravity(Gravity.CENTER);
		mDragGridView.setStretchMode(GridView.NO_STRETCH);
		mDragGridView.setNumColumns(ShowImageActivity.selectedPhotoList.size());
		mDragAdapter = new DragAdapter(getApplicationContext(), ShowImageActivity.selectedPhotoList,mDragGridView);
		mDragGridView.setAdapter(mDragAdapter);

		mDragGridView.setOnReorderItemsListener(new OnReorderItemsListener() {
			@Override
			public void reorderItems(int from, int to) {
				AndroidImageFile temp = ShowImageActivity.selectedPhotoList.get(from);
				//这里的处理需要注意下
				if(from < to){
					for(int i=from; i<to; i++){
						Collections.swap(ShowImageActivity.selectedPhotoList, i, i+1);
					}
				}else if(from > to){
					for(int i=from; i>to; i--){
						Collections.swap(ShowImageActivity.selectedPhotoList, i, i-1);
					}
				}
				ShowImageActivity.selectedPhotoList.set(to, temp);
				//设置新到的item隐藏，不用调用notifyDataSetChanged来刷新界面，因为setItemHide方法里面调用了
				mDragAdapter.setHideItem(-1);
			}
		});

		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				galleryHorizontalView.scrollTo(ShowImageActivity.currentScrollX, 0);
			}
		},10);
		updateSelectedPhotoList();
	}

	private void invalidateNextStep() {
		/// TODO Auto-generated method stub
		if(ShowImageActivity.showNextButton){  
			nextStep.setVisibility(View.VISIBLE); 
			if (ShowImageActivity.selectedPhotoList!=null&&ShowImageActivity.selectedPhotoList.size()==bookProduct.getNumOfPictures()){
				nextStep.setEnabled(true);  
				nextStep.setBackgroundResource(drawable.button_blue_style);
			} else{  
				nextStep.setEnabled(false);  
				nextStep.setBackgroundResource(drawable.greypressed);
			}
		}	else{  
			nextStep.setVisibility(View.INVISIBLE); 
		}
	}
	public void updateSelectedPhotoList() { //同时更新下方列表的显示情况
		selectedPhotoListNum.setText(getResources().getString(R.string.T_Selected_text)
				+ShowImageActivity.selectedPhotoList.size()
				+getResources().getString(R.string.T_Split_text)
				+bookProduct.getNumOfPictures()
				+getResources().getString(R.string.T_Page_text));
		RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mGroupGridView
				.getLayoutParams();
		if(!(ShowImageActivity.selectedPhotoList.size()>0)){
			//if(!(selectedPhotoList.size()>0)){
			layoutParams.bottomMargin = 0;
			layoutParams.setMargins(0, 0, 0, 0);
			mGroupGridView.setLayoutParams(layoutParams);
			relativeLayoutOfSelectedPhotoList.setVisibility(View.INVISIBLE);
		}else{
//			int height = relativeLayoutOfSelectedPhotoList.getHeight();
//			Log.i("msg", height+"");
			layoutParams.bottomMargin = selected_photo_height;
			Resources resources = getResources();
			float selectedPhotoListTitleHeight = resources.getDimension(R.dimen.selectedPhotoListTitleHeight);
			layoutParams.setMargins(0, 0, 0,(int)(selected_photo_height+selectedPhotoListTitleHeight)+25);//当selectedlist里面有照片时，显示所有照片的layout需要改变大小来适应
			mGroupGridView.setLayoutParams(layoutParams);
			relativeLayoutOfSelectedPhotoList.setVisibility(View.VISIBLE);
			
		}
		if(mDragAdapter!=null)
			mDragAdapter.notifyDataSetChanged();
		invalidateNextStep();
	}


	/**
	 * 组装分组界面GridView的数据源，因为我们扫描手机的时候将图片信息放在HashMap中
	 * 所以需要遍历HashMap将数据组装成List
	 * 
	 * @param mGroupMap
	 * @return
	 */
	private List<AlbumBean> subGroupOfImage(HashMap<String, List<AndroidImageFile>> mGroupMap){
		List<AlbumBean> list = new ArrayList<AlbumBean>();
		if(mGroupMap.size() == 0){
			showToast(getResources().getString(R.string.T_NoPhotoInSD));
			return list;
		}
		Iterator<Map.Entry<String, List<AndroidImageFile>>> it = mGroupMap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, List<AndroidImageFile>> entry = it.next();
			AlbumBean mImageBean = new AlbumBean();
			String key = entry.getKey();
			List<AndroidImageFile> value = entry.getValue();
			String folderName = key.substring(key.lastIndexOf("/")+1);
			mImageBean.setFolderPath(key);
			mImageBean.setFolderName(folderName);
			mImageBean.setImageCounts(value.size());
			mImageBean.setTopImageAIF(value.get(0));//获取该组的第一张图片

			list.add(mImageBean);
		}
		return list;
	}
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}
}
